package org.feng.controller;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.feng.entity.SysDept;
import org.feng.entity.SysJob;
import org.feng.entity.SysRole;
import org.feng.entity.SysUser;
import org.feng.entity.query.UpdatePasswordQuery;
import org.feng.entity.result.SysUserInfoResult;
import org.feng.entity.result.UploadResult;
import org.feng.service.ISysDeptService;
import org.feng.service.ISysJobService;
import org.feng.service.ISysRoleService;
import org.feng.condition.Condition;
import org.feng.utils.PoiUtils;
import org.feng.annotation.AccessLog;
import org.feng.base.entity.Result;
import org.feng.support.UploadSupport;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.feng.service.ISysUserService;
import org.feng.base.controller.BaseController;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;

import java.util.*;

/**
 * 用户表
 *
 * @author : FengShuai
 * @since : 2024/6/27 9:24
 */
@RestController
@RequestMapping("/system/sysUser")
@Tag(name = "用户")
public class SysUserController extends BaseController {

    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysDeptService sysDeptService;
    @Resource
    private ISysJobService sysJobService;
    @Resource
    private ISysRoleService sysRoleService;
    @Value("${sa-token.aes-key}")
    private String aesKey;
    @Resource
    private UploadSupport uploadSupport;

    @GetMapping("/download")
    @Operation(summary = "查询用户列表")
    public void download(SysUser sysUser) {
        List<SysUser> userList = sysUserService.list();
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("username", "用户名");
        map.put("avatar", "头像");
        map.put("password", "密码");
        map.put("name", "真实姓名");
        map.put("phone", "手机号");
        map.put("sex", "性别");
        PoiUtils.exportExcel(map, userList);
    }

    @PostMapping("/updateAvatar")
    @Operation(summary = "修改头像")
    public Result<String> updateAvatar(@RequestParam MultipartFile file) {
        UploadResult uploadResult = uploadSupport.build().putFile(file);
        SysUser sysUser = sysUserService.getById(StpUtil.getLoginIdAsString());
        sysUser.setAvatar(uploadResult.getFileUrl());
        sysUserService.updateById(sysUser);
        return Result.success(uploadResult.getFileUrl());
    }

    @GetMapping("/pageList")
    @Operation(summary = "分页列表")
    public Result<IPage<SysUser>> pageList(SysUser sysUser) {
        ArrayList<String> list = new ArrayList<>();
        if (StrUtil.isNotEmpty(sysUser.getDeptId())) {
            sysDeptService.getStudentDeptId(sysUser.getDeptId(), list);
        }
        return Result.success(sysUserService.page(Condition.getPage(), Wrappers.<SysUser>lambdaQuery()
                .eq(StrUtil.isNotEmpty(sysUser.getUsername()), SysUser::getUsername, sysUser.getUsername())
                .eq(StrUtil.isNotEmpty(sysUser.getName()), SysUser::getName, sysUser.getName())
                .eq(StrUtil.isNotEmpty(sysUser.getPhone()), SysUser::getPhone, sysUser.getPhone())
                .in(!list.isEmpty(), SysUser::getDeptId, list)));
    }

    /**
     * 修改密码
     *
     * @param updatePasswordQuery
     * @return
     */
    @PostMapping("/updatePassword")
    @AccessLog("更改密码")
    @Operation(summary = "更改密码")
    public Result<Boolean> updatePassword(@RequestBody UpdatePasswordQuery updatePasswordQuery) {
        SysUser sysUser = sysUserService.getById(StpUtil.getLoginIdAsString());
        if (!sysUser.getPassword().equals(SaSecureUtil.aesEncrypt(aesKey, updatePasswordQuery.getOldPassword()))) {
            return Result.error("原密码错误");
        }
        if (!updatePasswordQuery.getAgainPassword().equals(updatePasswordQuery.getNewPassword())) {
            return Result.error("两次密码不一致");
        }
        sysUser.setPassword(SaSecureUtil.aesEncrypt(aesKey, updatePasswordQuery.getNewPassword()));
        return Result.success(sysUserService.updateById(sysUser));
    }

    /**
     * 重置密码
     *
     * @param ids
     * @return
     */
    @GetMapping("/resetPassword")
    @AccessLog("重置密码")
    @Operation(summary = "重置密码")
    public Result<Boolean> resetPassword(@RequestParam("ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        return Result.status(sysUserService.update(Wrappers.<SysUser>lambdaUpdate()
                .in(SysUser::getId, idList)
                .set(SysUser::getPassword, SaSecureUtil.aesEncrypt(aesKey, "123456"))));
    }

    @GetMapping("/list")
    @Operation(summary = "列表")
    public Result<List<SysUser>> list(SysUser sysUser) {
        return Result.success(sysUserService.list(Wrappers.lambdaQuery(sysUser)));
    }

    @PostMapping("/save")
    @AccessLog("添加用户")
    @Operation(summary = "保存")
    public Result<Boolean> save(@RequestBody SysUser sysUser) {
        sysUser.setPassword(SaSecureUtil.aesEncrypt(aesKey, "123456"));
        return Result.status(sysUserService.save(sysUser));
    }

    @PostMapping("/update")
    @AccessLog("更新用户")
    @Operation(summary = "更新")
    public Result<Boolean> update(@RequestBody SysUser sysUser) {
        return Result.status(sysUserService.updateById(sysUser));
    }

    @GetMapping("/remove")
    @AccessLog("删除用户")
    @Operation(summary = "删除")
    public Result<Boolean> remove(@RequestParam("ids") String ids) {
        return Result.status(sysUserService.removeBatchByIds(Arrays.asList(ids.split(","))));
    }

    @GetMapping("/userInfo")
    @Operation(summary = "用户信息")
    public Result<SysUserInfoResult> userInfo() {
        SysUser sysUser = sysUserService.getById(StpUtil.getLoginIdAsString());
        SysUserInfoResult result = toBean(sysUser, SysUserInfoResult.class);
        SysJob sysJob = sysJobService.getById(sysUser.getJobId());
        SysDept sysDept = sysDeptService.getById(sysUser.getDeptId());
        SysRole sysRole = sysRoleService.getById(sysUser.getRoleId());
        result.setRoleName(sysRole.getName());
        result.setJobName(sysJob.getName());
        result.setDeptName(sysDept.getName());
        return Result.success(result);
    }
}
